package kyFtp.process
{
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import kyFtp.events.FtpProgressEvent;
	import kyFtp.events.HandleFileEvent;
	import kyFtp.request.FtpRequest;
	import kyFtp.request.FtpRequestType;
	import kyFtp.response.Response;
	import kyFtp.response.ResponseType;
	import kyFtp.utils.ExtendSocket;
	import kyFtp.utils.ProgressData;

	/**
	 * @author 秦家洋
	 * @E-mail: develop@kongyue.cc
	 * 创建时间：2015-7-3 上午11:28:53
	 * 
	 */
	public class DownloadProcess extends ProcessBase
	{
		private var pasvSock:ExtendSocket;
		private var serverFileName:String;
		private var total:int;
		private var loaded:int;
		private var saveFile:File;
		private var fileStream:FileStream;
		private var fileData:ByteArray;
		private var timer:Timer;
		private var oldNum:Number=0;
		private var old2Num:Number=0;
		private var progress:Number=0;
		private var pd:ProgressData = new ProgressData();
		public function DownloadProcess(serverFileName:String,saveFile:File)
		{
			this.serverFileName = serverFileName;
			this.saveFile = saveFile;
			
		}
		public override function responseHandler(res:Response):void
		{
			switch(res.code)
			{
				case ResponseType.COMMAND_OK:
					this.sendCmd(FtpRequest.parse(FtpRequestType.SIZE,serverFileName));
					break;
				case ResponseType.FILE_STATUS:
					total = parseInt(res.message);
					//trace("要下载的文件大小:"+total);
					this.sendCmd(FtpRequest.parse(FtpRequestType.PASV));
					break;
				case ResponseType.ENTERING_PASV:
					fileStream = new FileStream();
					fileStream.open(saveFile, FileMode.WRITE);
					pasvSock = ExtendSocket.parsePASVSock(res.message);
					pasvSock.addEventListener(Event.CONNECT, onPasvConnected);
					pasvSock.addEventListener(ProgressEvent.SOCKET_DATA, onPasvData);
					break;
				case ResponseType.DATA_CONN_CLOSE:
					trace("下载完成");
					clear();
					dispatchEvent(new HandleFileEvent(HandleFileEvent.DOWNLOAD_SUCCESS));
					break;
				case ResponseType.FILE_STATUS_OK:
					trace("文件准备好了，打开数据连接");
					timer = new Timer(1000);
					timer.addEventListener(TimerEvent.TIMER,run);
					timer.start();
					break;
				default:
					//nothing
			}
		}
		public override function sendRequest():void
		{
			this.sendCmd(FtpRequest.parse(FtpRequestType.BINARY));
		}
		private function onPasvConnected(e:Event):void
		{
			this.sendCmd(FtpRequest.parse(FtpRequestType.RETR, serverFileName));
		}
		
		private function onPasvData(e:ProgressEvent):void
		{
			fileData = new ByteArray();
			pasvSock.readBytes(fileData, 0, pasvSock.bytesAvailable);
			loaded+=fileData.length;
			fileStream.writeBytes(fileData, 0, fileData.bytesAvailable);
			progress = Math.floor(loaded/total*10000)/100;
			if(oldNum==0)
				oldNum = loaded;
			old2Num = loaded;
		}
		private function run(e:TimerEvent):void
		{
			var speed:Number = Math.floor((old2Num - oldNum)/1024);
			oldNum = 0;
			pd.total = total;
			pd.loaded = loaded;
			pd.speed = speed;
			pd.progress = progress;
			dispatchEvent(new FtpProgressEvent(FtpProgressEvent.PROGRESS,pd));
		}
		private function clear():void
		{
			if(fileStream)
			{
				fileStream.close();
				fileStream=null;
			}
			if(pasvSock)
			{
				if(pasvSock.connected)
					pasvSock.close();
				pasvSock.removeEventListener(Event.CONNECT, onPasvConnected);
				pasvSock.removeEventListener(ProgressEvent.SOCKET_DATA, onPasvData);
				pasvSock = null;
			}
			if(timer)
			{
				timer.stop();
				timer.removeEventListener(TimerEvent.TIMER,run);
				timer = null;
			}
		}
	}
}